<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联租金表ID（对应租金记录）" prop="rentId">
        <el-input v-model="queryParams.rentId" placeholder="请输入关联租金表ID（对应租金记录）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="调整前租金金额（单位：元）" prop="oldRent">
        <el-input v-model="queryParams.oldRent" placeholder="请输入调整前租金金额（单位：元）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="调整后租金金额（单位：元）" prop="newRent">
        <el-input v-model="queryParams.newRent" placeholder="请输入调整后租金金额（单位：元）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请人ID（关联用户表）" prop="applicantId">
        <el-input v-model="queryParams.applicantId" placeholder="请输入申请人ID（关联用户表）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审批人ID（关联用户表，审批完成前为空）" prop="approverId">
        <el-input v-model="queryParams.approverId" placeholder="请输入审批人ID（关联用户表，审批完成前为空）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="租金调整原因说明（500字以内）" prop="applyReason">
        <el-input v-model="queryParams.applyReason" placeholder="请输入租金调整原因说明（500字以内）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="驳回原因说明（仅驳回时需填写）" prop="rejectReason">
        <el-input v-model="queryParams.rejectReason" placeholder="请输入驳回原因说明（仅驳回时需填写）" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请提交时间" prop="applyTime">
        <el-date-picker v-model="queryParams.applyTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="审批操作时间（通过/驳回时更新）" prop="auditTime">
        <el-date-picker v-model="queryParams.auditTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                  >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                  >导出</el-button>

                  <!-- <el-button @click="connect" type="primary" :disabled="ws&&ws.readyState===1"> -->
                   
            <!-- <el-button @click="exit" type="danger">断开</el-button> -->

      </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="审批流程唯一标识" align="center" prop="id" />
      <!-- <el-table-column label="图片" align="center" prop="housePicture" /> -->

      <el-table-column label="图片" align="center" prop="housePicture" width="150">
  <template v-slot="scope">
    <el-image 
      :src="scope.row.housePicture"
      :preview-src-list="[scope.row.housePicture]"
      fit="cover"
      style="width: 100px; height: 100px"
    >
      <div slot="error" class="image-error-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image>
  </template>
</el-table-column>

      <!-- <el-table-column label="关联租金表ID（对应租金记录）" align="center" prop="rentId" />
      <el-table-column label="调整前租金金额（单位：元）" align="center" prop="oldRent" />
      <el-table-column label="调整后租金金额（单位：元）" align="center" prop="newRent" />
      <el-table-column label="申请人ID（关联用户表）" align="center" prop="applicantId" />
      <el-table-column label="审批人ID（关联用户表，审批完成前为空）" align="center" prop="approverId" />
      <el-table-column label="租金调整原因说明（500字以内）" align="center" prop="applyReason" />
      <el-table-column label="审批状态（PENDING-待审批/APPROVED-已通过/REJECTED-已拒绝）" align="center" prop="auditStatus" />
      <el-table-column label="驳回原因说明（仅驳回时需填写）" align="center" prop="rejectReason" /> -->
      <!-- <el-table-column label="申请提交时间" align="center" prop="applyTime" width="180" > 
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="审批操作时间（通过/驳回时更新）" align="center" prop="auditTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.auditTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.auditId)"
                     >申请</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     >删除</el-button>


        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <RentAdjustAuditForm ref="formRef" @success="getList" />
    </div>
</template>

<script>
import * as RentAdjustAuditApi from '@/api/system/rentadjustaudit';
import RentAdjustAuditForm from './RentAdjustAuditForm.vue';
import {getNowDateTime} from "@/utils/ruoyi";
import {getAccessToken} from "@/utils/auth";

export default {
  name: "RentAdjustAudit",
  components: {
          RentAdjustAuditForm,

  },
  data() {
    return {
 houseList: [], //  独立存储房屋数据
    houseTotal: 0, //  独立存储房屋总条数

      list: [], // 存储房屋信息列表
      total: 0, // 总条数
      loading: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },


      url: "",
      sendText: "",
      content: "",
      ws: null,
      userList: [], // 用户列表
      sendUserId: null, // 发给谁，默认所有人

 // 新增连接状态
 isConnected: false,
    connectionStatus: 'disconnected', // 可选更详细状态
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
              // 总条数
        total: 0,
      // 租金调整审批流程记录表（记录租金调整申请和审批流程）列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
                    pageNo: 1,
            pageSize: 10,
        rentId: null,
        oldRent: null,
        newRent: null,
        applicantId: null,
        approverId: null,
        applyReason: null,
        auditStatus: null,
        rejectReason: null,
        applyTime: [],
        auditTime: [],
        createTime: [],
      },
            };
  },
  created() {
    this.getList();
  this.getHouseList(); 
    const wsUrl = process.env.VUE_APP_BASE_API + "/infra/ws" + '?token=' + getAccessToken();
    this.url = wsUrl.replace("http", "ws");
    // 获取用户精简信息列表
    listSimpleUsers().then(res => {
      this.userList = res.data;


// WebSocket初始化
const wsUrl = process.env.VUE_APP_BASE_API + "/infra/ws" + '?token=' + getAccessToken();
  this.url = wsUrl.replace("http", "ws");
   // 自动建立连接
   this.connect(); // 新增此行

    // 获取用户精简信息列表
  listSimpleUsers().then(res => {
    this.userList = res.data;

    });
  });
},
  methods: {
    //  /** houseinfo查询列表 */
    // async getHouseList() {
    //   try {
    //   this.loading = true;
    //     //  const res = await HouseInfoApi.getHouseInfoPage(this.queryParams);
    //     // this.list = res.data.records;
    //     // this.total = res.data.total;
    //       // 过滤无效参数
    //   const filteredParams = Object.fromEntries(
    //     Object.entries(this.queryParams)
    //       .filter(([_, v]) => v !== null && v !== '')
    //   );
      
    //   const res = await HouseInfoApi.getHouseInfoPage(filteredParams);
    //   this.houseList = res.data.records; 
    //   this.houseTotal = res.data.total; 

    //   } finally {
    //     this.loading = false;
    //   }
    // },
 /** 处理申请操作 */
   handleApply() { 
       this.$refs.shenpi.open()
  },
    /** 查询列表 */
    async getList() {
      try {
      this.loading = true;
              const res = await RentAdjustAuditApi.getRentAdjustAuditPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
        console.log(res);
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const auditId = row.auditId;
      await this.$modal.confirm('是否确认删除租金调整审批流程记录表（记录租金调整申请和审批流程）编号为"' + auditId + '"的数据项?')
      try {
       await RentAdjustAuditApi.deleteRentAdjustAudit(auditId);
       await this.getList();
       this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有租金调整审批流程记录表（记录租金调整申请和审批流程）数据项?');
      try {
        this.exportLoading = true;
        const data = await RentAdjustAuditApi.exportRentAdjustAuditExcel(this.queryParams);
        this.$download.excel(data, '租金调整审批流程记录表（记录租金调整申请和审批流程）.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    // 模拟测试消息
    testMessageHandling() {
  const testMessages = [
    // 合法用例
    { 
      type: 'RentAdjustAudit',
      content: JSON.stringify({
        auditId: 1001,
        auditStatus: 'APPROVED',
        // newRent: 6500
      })
    },
     // 非法消息应包含完整结构
     {
      type: 'RentAdjustAudit',
      content: JSON.stringify({ 
        auditId: 'invalid_id', // 错误类型
        auditStatus: 'UNKNOWN'
      })
    }
  ];

  testMessages.forEach((msg, index) => {
    setTimeout(() => {
      this.ws.onmessage({ data: JSON.stringify(msg) });
    }, index * 1500);
  });
},
  /** 处理租金审批消息 */
  handleRentAuditMessage(message) {
    try {
        // 检查消息内容类型
        if (typeof message.content !== 'string' && typeof message.content !== 'object') {
            throw new Error(`无效内容类型: ${typeof message.content}`);
        }

        // 如果 content 是字符串，尝试解析为 JSON
        let content;
        if (typeof message.content === 'string') {
            // 检查是否为空字符串
            if (!message.content.trim()) {
                throw new Error('消息内容为空字符串');
            }
            // 检查是否为有效的 JSON 格式
            // if (!/^\{.*\}$/.test(message.content)) {
            //     throw new Error('内容不是有效的JSON对象');
            // }
            content = JSON.parse(message.content);
        } else {
            // 如果 content 已经是对象，直接使用
            content = message.content;
        }

        // 检查 content 是否为有效的 JSON 对象
        // if (!content || typeof content !== 'object') {
        //     throw new Error('内容必须是有效JSON对象');
        // }

        // 校验必要字段
        // const requiredFields = ['auditId', 'auditStatus'];
        // const missingFields = requiredFields.filter(field => !(field in content));
        // if (missingFields.length > 0) {
        //     throw new Error(`缺失必要字段: ${missingFields.join(', ')}`);
        // }

        // 校验字段类型
        // if (!Number.isInteger(content.auditId)) {
        //     throw new Error('auditId 必须是整数');
        // }
        // if (!['PENDING', 'APPROVED', 'REJECTED'].includes(content.auditStatus)) {
        //     throw new Error('auditStatus 必须是 PENDING、APPROVED 或 REJECTED');
        // }

        // 更新数据逻辑
        const now = new Date().toISOString();
        const targetIndex = this.list.findIndex(item => item.auditId === content.auditId);

        if (targetIndex > -1) {
            // 如果记录已存在，更新记录
            this.$set(this.list, targetIndex, {
                ...this.list[targetIndex],
                ...content,
                auditTime: content.auditTime || now,
                _updateTime: now // 添加更新时间追踪
            });
        } else {
            // 如果记录不存在，添加新记录
            this.list.unshift({
                ...content,
                createTime: content.createTime || now,
                auditTime: content.auditTime || now
            });
        }

        // 显示通知
        this.$notify({
            title: '状态更新',
            type: content.auditStatus === 'REJECTED' ? 'error' : 'success',
            message: `审批记录 #${content.auditId} 已更新为 ${content.auditStatus}`,
            duration: 2500,
            customClass: `audit-notice ${content.auditStatus.toLowerCase()}`
        });

    } catch (e) {
        // 错误处理
        // console.error('[消息处理]', e);
        // this.$notify.error({
        //     title: `消息处理失败 (${e.name})`,
        //     message: `${e.message}<br>原始数据: ${JSON.stringify(message)}`,
        //     dangerouslyUseHTMLString: true,
        //     duration: 5000
        // });
    }
},

// 推荐使用更清晰的事件处理结构
setupWebSocketHandlers() {
  this.ws.onopen = this.handleWebSocketOpen.bind(this);
  this.ws.onmessage = this.handleWebSocketMessage.bind(this);
  this.ws.onerror = this.handleWebSocketError.bind(this);
  this.ws.onclose = this.handleWebSocketClose.bind(this);
},

// 单独定义处理方法
handleWebSocketOpen(event) {
  this.isConnected = true;
  this.connectionStatus = 'connected';
  console.log('WebSocket连接成功', event);
},

handleWebSocketError(error) {
  this.connectionStatus = 'error';
  console.error('WebSocket错误', error);
},


/** 发起连接 */
connect() {
  if (!('WebSocket' in window)) { // 修复判断语法
    this.$modal.msgError("您的浏览器不支持WebSocket");
    return;
  }
  
  // 清除旧连接
  if (this.ws) {
    this.ws.close();
    this.ws = null;
    this.isConnected = false;
  }
       // 建立连接
  this.ws = new WebSocket(this.url);
     
  // 监听 open 事件（修复这里）
  this.ws.onopen = (event) => {
    this.isConnected = true;
    this.connectionStatus = 'connected';
    this.content += "\n**********************连接开始**********************\n";


// ws.onerror = () => {
//   this.connectionStatus = 'error';
// }
 // 统一使用this.ws引用
 this.ws.onerror = (error) => {
    this.connectionStats.lastError = {
      time: new Date(),
      message: error.message
    };
  };
      };
      // 监听 message 事件
      this.ws.onmessage = (event) => {
        try {
          const data = event.data;
          // 1. 收到心跳
          if (data === 'pong') return;
          const message = JSON.parse(data);
    
    // 处理 RentAdjustAudit 类型消息
    if (message.type === 'RentAdjustAudit') {
      this.handleRentAuditMessage(message);
      return;
    }
      
          // 2.2 消息类型：demo-message-receive
          if (type === 'demo-message-receive') {
            const single = content.single;
            this.content = this.content + "接收时间：" + getNowDateTime() + "\n" +
                `【${single ? '单发' : '群发'}】用户编号(${content.fromUserId})：${content.text}` + "\n";
            return;
          }
          // 2.3 消息类型：notice-push
          if (type === 'notice-push') {
            this.content = this.content + "接收时间：" + getNowDateTime() + "\n" + `【系统通知】：${content.title}` + "\n";
            return;
          }
          this.$modal.msgError('未处理消息：' + data);
        } catch (error) {
          this.$modal.msgError('处理消息发生异常：' + event.data);
          console.error(error);
        }
      };
      // 监听 close 事件
      this.ws.onclose = (event) => {
        this.isConnected = false;
        if (event.wasClean) return;
  console.log('意外断开，5秒后重连...');
  setTimeout(() => this.connect(), 5000);
        this.content = this.content + "**********************连接关闭**********************\n";
      };
      // 监听 error 事件
      this.ws.error = (event) => {
        this.content = this.content + "**********************连接异常**********************\n";
      };
    },
    
    /** 关闭连接 */
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
        this.isConnected = false; // 确保状态同步
      }
    },
    /** 发送消息 */
    send() {
      if (!this.ws || this.ws.readyState !== 1) {
        this.$modal.msgError("未连接到服务器");
        return;
      }
      if (!this.sendText) {
        this.$modal.msgError("请输入发送内容");
        return;
      }

      // 1.1 先 JSON 化 message 消息内容
      const messageContent = JSON.stringify({
        text: this.sendText,
        toUserId: this.sendUserId
      });
      // 1.2 再 JSON 化整个消息
      const jsonMessage = JSON.stringify({
        type: 'demo-message-send',
        content: messageContent
      });
      // 2. 最后发送消息
      this.ws.send(jsonMessage);
      this.sendText = '';
    }

              }
};
</script>
